package com.company.permission.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 直接加载mybatis-config.xml，不使用properties
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);

            System.out.println("=== Mybatis配置初始化 ===");
            System.out.println("加载配置文件: " + resource);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            System.out.println("数据库URL: " + sqlSessionFactory.getConfiguration().getEnvironment().getDataSource().getConnection().getMetaData().getURL());
            System.out.println("=== Mybatis初始化完成 ===");

        } catch (Exception e) {
            System.err.println("Mybatis初始化失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("初始化Mybatis失败", e);
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}